﻿using System;
using System.ComponentModel;

namespace Esponce.QRCode.Content
{
	public abstract class ContentFormatBase<T> : IContentFormat, INotifyPropertyChanged where T : class, IContentFormat
	{
		#region Public properties
		/// <summary>
		/// Gets or sets a value indicating whether loading is in progress.
		/// </summary>
		public bool IsLoading
		{
			get
			{
				return this.isLoading;
			}
			set
			{
				if (this.isLoading != value)
				{
					this.isLoading = value;
					OnPropertyChanged("IsLoading");
				}
			}
		}
		private bool isLoading;

		/// <summary>
		/// Gets or sets the original content.
		/// </summary>
		public string Content
		{
			get
			{
				return this.content;
			}
			set
			{
				if (this.content != value)
				{
					this.content = value;
					OnPropertyChanged("Content");
				}
			}
		}
		private string content;
		#endregion

		#region Static methods
		public static bool TryParse(string content, out T result)
		{
			result = Activator.CreateInstance<T>();

			try
			{
				(result as IContentFormat).Parse(content);
				return true;
			}
			catch
			{
				result = null;
				return false;
			}
		}
		#endregion

		#region IContentFormat Members
		public virtual void Parse(string content)
		{
			if (string.IsNullOrEmpty(content))
			{
				throw new ArgumentException("Content is missing!", "content");
			}

			this.Content = content;
		}

		public abstract string Build();

		public abstract string GetFriendlyName();

		public override string ToString()
		{
			return Build();
		}
		#endregion

		#region INotifyPropertyChanged Members
		public event PropertyChangedEventHandler PropertyChanged;
		protected virtual void OnPropertyChanged(string propertyName)
		{
			if (PropertyChanged != null)
			{
				PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
			}
		}
		#endregion
	}
}
